package com.histone.heartbeat.service;

import com.alibaba.fastjson.JSONObject;
import com.histone.heartbeat.dao.UrlDao;
import com.histone.heartbeat.dao.UserDao;
import com.histone.heartbeat.pojo.*;
import com.histone.heartbeat.pojo.resp.ImageMessage;
import com.histone.heartbeat.pojo.resp.TextMessage;
import com.histone.heartbeat.util.WeixinMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信接收、发送消息
 */
@Service
@Slf4j
public class MsgService {
    @Autowired
    private UrlDao urlDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WxApi wxApi;

    @Autowired
    private WeixinMessageUtil weixinMessageUtil;

    @Autowired
    private RestTemplate restTemplate;

    public String receiveMsg(HttpServletRequest request) throws Exception{
        log.info("------------微信消息开始处理-------------");
        // 返回给微信服务器的消息,默认为空串
        String respMessage = "";

        // xml分析 调用消息工具类MessageUtil解析微信发来的xml格式的消息，解析的结果放在HashMap里；
        Map<String, String> map = weixinMessageUtil.parseXml(request);
        log.info("wexin get message is {}", map);
        // 获取用户 openid ， 并用作 userid
        String openid = map.get("FromUserName");

        // 消息类型
        String msgType = map.get("MsgType");

        // 分析用户发送的消息类型，并作出相应的处理
        switch (MsgType.valueOf(msgType)) {
            // 文本消息
            case text:
                String respContent = "添加网址成功，网址故障时将会收到报警信息";
                String webUrl = map.get("Content");
                try {
                    URL url = new URL(webUrl);
                    InputStream inputStream = url.openStream();

                    //保存到数据库中
                    UrlEntity urlEntity = new UrlEntity();
                    urlEntity.setUrl(webUrl);
                    urlEntity.setCreateDate(LocalDate.now());
                    urlEntity.setUserid(openid);
                    urlEntity.setLevel(3);
                    urlEntity.setName("网址");

                    urlDao.save(urlEntity);
                } catch (IOException e) {
                    log.error("add url error [}, url {}", e.getMessage(), webUrl);
                    respContent = "添加网址失败，请检查输入是否正确";
                }

                TextMessage textMessage = new TextMessage(map.get("ToUserName"), openid, respContent);
                respMessage = weixinMessageUtil.textMessageToXml(textMessage);
                break;
            // 事件推送(当用户主动点击菜单，或者扫面二维码等事件)
            case event:
                // 进一步分析事件类型
                String eventType = map.get("Event");
                switch (MsgType.EventType.valueOf(eventType)) {
                    // 关注
                    case subscribe:
                        //新建用户
                        UserEntity user = new UserEntity();
                        user.setId(openid);
                        user.setCreateDate(LocalDate.now());

                        userDao.save(user);

                        ImageMessage imageMessage = new ImageMessage(map.get("ToUserName"), openid, "2c0un7zIt2Rnt5R4-NsFt7TgaZ0EyRiepXUVeZbCqBs");
                        respMessage = weixinMessageUtil.imageMessageToXml(imageMessage);
                        break;
                    // 取关
                    case unsubscribe:
                        // 删除相关数据
                        urlDao.deleteByUserid(openid);
                        userDao.deleteById(openid);
                        break;
                }

        }

        log.info("respMessage is {}", respMessage);
        return respMessage;
    }

    /**
     * 发送模板消息
     * @param openid        接收者openid
     * @param templateid    模板id
     * @param url           消息链接
     * @param first         模板占位符
     * @param keyword1      模板占位符
     * @param keyword2      模板占位符
     * @param remark        模板占位符
     */
    public void sendTemplateMsg(String openid, String templateid, String url,
                                String first, String keyword1, String keyword2, String remark) {
        String token = tokenService.getToken();
        String templateUrl = wxApi.getTemplate_send().replaceAll("ACCESS_TOKEN", token);

        Map<String, Map> data = new HashMap<>();

        genData("first", first, data);
        genData("keyword1", keyword1, data);
        genData("keyword2", keyword2, data);
        genData("remark", remark, data);

        JSONObject param = new JSONObject();
        param.fluentPut("touser", openid)
                .fluentPut("template_id", templateid)
                .fluentPut("url", url)
                .fluentPut("data", data);

        restTemplate.postForObject(templateUrl, param, JSONObject.class);
    }

    public void genData(String key, String value, Map data){
        Map<String,String> keyMap = new HashMap<>();
        keyMap.put("value", value);
        keyMap.put("color", "#173177");

        data.put(key, keyMap);
    }

}
